package com.gxa.servlet;

import com.alibaba.fastjson.JSON;
import com.gxa.dto.ResponseResult;
import com.gxa.entity.Build;
import com.gxa.exception.ErrorType;
import com.gxa.service.BuildService;
import com.gxa.service.impl.BuildServiceImpl;
import com.gxa.utils.WriteJson;
import com.sun.org.apache.bcel.internal.generic.NEW;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/build/*")
public class BuildServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI(); // 获取uri
        String path = uri.substring(uri.lastIndexOf("/")); // 截取数据接口

        // 全局声明业务逻辑层
        BuildService buildService = new BuildServiceImpl();

        if ("/queryAllBuidByCommu".equals(path)){
            doQueryAllBuidByCommu(req,resp,buildService);
        } else if ("/queryAllUnitByBuildAndComm".equals(path)){
            doQueryAllUnitByBuildAndComm(req,resp,buildService);
        } else if ("/queryAllBuid".equals(path)) {
            doQueryAllBuid(req,resp,buildService);
        } else if ("/queryAllBuildByPage".equals(path)) {
            doQueryAllBuidByPage(req,resp,buildService);
        } else if ("/addBuild".equals(path)) {
            doAddBuild(req,resp,buildService);
        } else if ("/editBuild".equals(path)) {
            doEditBuild(req,resp,buildService);
        } else if ("/delBuildById".equals(path)) {
            doDelBuildById(req,resp,buildService);
        }
    }

    /**
     * 通过id删除对应的build记录
     * @param req
     * @param resp
     * @param buildService
     */
    private void doDelBuildById(HttpServletRequest req, HttpServletResponse resp, BuildService buildService) {
        // 1、获取参数
        String bid = req.getParameter("bid");

        // 2、调用业务逻辑层完成业务
        boolean delBuildById = buildService.delBuildByBid(bid);

        // 3、封装返回结果
        if (delBuildById){
            ResponseResult<Boolean> result = new ResponseResult<>(ErrorType.SUCCESS, 1, delBuildById);
            WriteJson.writeJson(result,resp);
        } else {
            ResponseResult<Boolean> result = new ResponseResult<>(ErrorType.FAILED_SAVE_PY_RESULT, 1, delBuildById);
            WriteJson.writeJson(result,resp);
        }
    }

    /**
     * 修改栋数
     * @param req
     * @param resp
     * @param buildService
     */
    private void doEditBuild(HttpServletRequest req, HttpServletResponse resp, BuildService buildService) {
        BufferedReader reader = null;
        String readLine = null;
        try {
            reader = req.getReader();
            readLine = reader.readLine();
            Build build = JSON.parseObject(readLine, Build.class);
            boolean editBuildResult =  buildService.editBuildByBuild(build);
            if (editBuildResult) {
                ResponseResult<Boolean> result = new ResponseResult<>(ErrorType.SUCCESS, 0, editBuildResult);
                WriteJson.writeJson(result,resp);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 新加栋数
     * @param req
     * @param resp
     * @param buildService
     */
    private void doAddBuild(HttpServletRequest req, HttpServletResponse resp, BuildService buildService) {
        // 1、获取参数
        // Json数据 从请求体里面获取JSON字符串，然后再解析为Java对象
        BufferedReader br = null;
        try {
            br = req.getReader();
            String params = br.readLine();  //json字符串
            //转为Java Build对象
            Build build = JSON.parseObject(params, Build.class);
            // 2、调用业务逻辑层完成业务
            boolean addBuildResult =  buildService.addBuild(build);
            // 3、封装结果
            ResponseResult<Boolean> result = new ResponseResult<>(ErrorType.SUCCESS, 0, addBuildResult);
            WriteJson.writeJson(result,resp);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 分页查询所有的栋数
     * @param req
     * @param resp
     * @param buildService
     */
    private void doQueryAllBuidByPage(HttpServletRequest req, HttpServletResponse resp, BuildService buildService) {
        // 1、获取参数
        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        List<Build> buildList = null;
        int counts = 0;

        try {
            // 2、调用方法完成业务
            // 2.1、分页查询所有的build
            buildList = buildService.queryAllBuildByPage(page,limit);
            // 2.2、查询数据表中记录的条数
            counts = buildService.queryCounts();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
        // 3、封装返回结果
        ResponseResult<List<Build>> result = new ResponseResult<>(ErrorType.SUCCESS, counts, buildList);
        WriteJson.writeJson(result,resp);
    }

    /**
     * 查询所有的栋数
     * @param req
     * @param resp
     * @param buildService
     */
    private void doQueryAllBuid(HttpServletRequest req, HttpServletResponse resp, BuildService buildService) {
        try {
            List<Build> buildList =  buildService.queryAllBuid();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
    }

    /**
     * 通过小区id 与 栋数id 选出所有的单元
     * @param req
     * @param resp
     * @param buildService
     */
    private void doQueryAllUnitByBuildAndComm(HttpServletRequest req, HttpServletResponse resp, BuildService buildService) {
        String cid = req.getParameter("cid");
        String bname = req.getParameter("bname");

        List<Build> buildList = null;
        try {
            buildList = buildService.queryAllUnitByBuildAndComm(cid, bname);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
        ResponseResult result = new ResponseResult(0, "success", 0, buildList);
        String toJSONString = JSON.toJSONString(result);
        writeJson(toJSONString,resp);

    }

    /**
     * 根据小区id查询小区所有的栋数
     * @param req
     * @param resp
     * @param buildService
     */
    private void doQueryAllBuidByCommu(HttpServletRequest req, HttpServletResponse resp, BuildService buildService) {
        // 1、获取参数

           /* BufferedReader reader = req.getReader();
            String s = reader.readLine();
            Build build = JSON.parseObject(s, Build.class);*/
            String cid = req.getParameter("cid");
            String cname = req.getParameter("cname");

        List<Build> buildList = null;
        try {
            buildList = buildService.queryAllBuidByCommu(cid, cname);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
        }
        ResponseResult result = new ResponseResult(0, "success",0, buildList);

            String toJSONString = JSON.toJSONString(result);
            writeJson(toJSONString,resp);



    }


    /**
     * 向客户端输出转化为json的数据流
     *
     * @param json_str json字符串
     * @param resp HttpServletResponse对象
     */
    public void writeJson(String json_str, HttpServletResponse resp) {

        // 设置输出的数据格式与
        resp.setContentType("text/json;charset=UTF-8");
        // 获取输出流对象
        PrintWriter out = null;
        try {
            out = resp.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        out.println(json_str);
    }
}
